<?php

namespace app\index\controller;

use app\data\model\ActArticleModel;
use app\index\service\LoginUserService;
use think\exception\HttpResponseException;

class DetailPage extends BaseController
{
    //详情
    //热门条数
    const DETAIL_HOT_ITEM_NUM = 4;
    //最新条数
    const DETAIL_NEWEST_ITEM_NUM = 4;
    //喜欢
    const DETAIL_LIKE_ITEM_NUM = 3;

    public function index($id)
    {
        //文章
        $this->detail = $this->getArticleOr404($id);
        //浏览量+1
        $this->detail->visitInc();
        //seo
        $this->siteTitle = $this->detail->title;
        $this->siteKeyWords = $this->detail->keywords;

        //热门文章，浏览量前100,随机4个
        //todo 隐私文章不推荐、不展示
        $hot_id_arr = ActArticleModel::order('read_count desc')->where('cat_id', 3)->limit(0, 100)->column('id');
        shuffle($hot_id_arr);
        $use_id_arr = array_slice($hot_id_arr, 0, self::DETAIL_HOT_ITEM_NUM);
        $this->hot = ActArticleModel::whereIn('id', $use_id_arr)->select();

        //最新文章最新100，随机4个
        //todo 隐私文章不推荐、不展示
        $this->newest = ActArticleModel::order('id desc')->where('cat_id', 3)->limit(0, self::DETAIL_NEWEST_ITEM_NUM)->select();

        //喜欢
        $all_id_arr = ActArticleModel::where('cat_id', 3)->column('id');
        shuffle($all_id_arr);
        $like_id_arr = array_slice($all_id_arr, 0, self::DETAIL_LIKE_ITEM_NUM);
        $this->like = ActArticleModel::whereIn('id', $like_id_arr)->select();

        $this->fetch('detail');
    }

    private function getArticleOr404($id)
    {
        $article = ActArticleModel::where('id', $id)->find();
        if (empty($article)) {
            throw new HttpResponseException(redirect('/404'));
        }
        return $article;

    }

    //文章评论
    public function articleComment($id)
    {
        if (!LoginUserService::ifLogin()) {
            $this->error('请登录后评论！');
        }
        $data = $this->_vali([
            'content.require' => '评论内容不能为空！',
            'name.require' => '姓名不能为空！',
            'email.require' => '邮箱不能为空！',
        ]);

        $article = $this->getArticleOr404($id);
        $article->addComment($data, LoginUserService::get('id'));

        $this->success('评论成功！');

    }

}